<template>
  <div>
    <div
      class="tinymce-editor"
      v-loading="loading"
      element-loading-text="上传中"
      element-loading-spinner="el-icon-loading"
    >
      <!-- 同一页面使用多个编辑器时必须传入id参数，否则只有第一个编辑器会生效-->
      <editor
        :id="editorId"
        v-model="editorValue"
        :disabled="disabledIn"
        :init="editorInit"
      />
      <div class="tinymce-upload-progress-box">
        <div class="display-upload-wrapper">
          <div class="innier-upload-wrapper"></div>
        </div>
        <!-- <el-progress type="circle" ref="uploadProgress" :color="colors" class="tinymce-upload-progress"
          :percentage="uploadPrecent" />
      </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import {
  uploadfile,
  breakpointUploadFile,
  addFile,
  checkFile,
} from "./../api/index";
import axios from "axios";
/*
使用public本地库
*/
// 引入tinymce主件
import tinymce from "../../public/tinymce/tinymce";
// 引入tinymce-vue组件
import Editor from "@tinymce/tinymce-vue";
import "tinymce/icons/default/icons";
// 必须引入主体才能汉化和显示
import "../../public/tinymce/themes/silver";
import "../../public/tinymce/zh_CN";
// import '../../../public/tinymce/icons/default/icons'
// 引入富文本编辑器主题的js和css
import "../../public/tinymce/themes/silver/theme.min";
import "../../public/tinymce/skins/ui/oxide/skin.min.css";
// 扩展插件
import "../../public/tinymce/plugins/image";
import "../../public/tinymce/plugins/link";
import "../../public/tinymce/plugins/code";
import "../../public/tinymce/plugins/table";
import "../../public/tinymce/plugins/lists";
import "../../public/tinymce/plugins/wordcount"; // 字数统计插件
import "../../public/tinymce/plugins/media"; // 插入视频插件
import "../../public/tinymce/plugins/template"; // 模板插件
import "../../public/tinymce/plugins/fullscreen";
import "../../public/tinymce/plugins/paste";
import "../../public/tinymce/plugins/preview";
import "../../public/tinymce/plugins/contextmenu";
import "../../public/tinymce/plugins/textcolor";
import "../../public/tinymce/plugins/indent2em/plugin"; // 首行缩进
import { uploadByPieces } from "./fenpian2";
let baseUrl = "http://139.215.190.237:8081/";
// 首行缩进插件需单独下载后将下载文件放在plugins下
export default {
  name: "Tinymce",
  components: {
    Editor,
  },
  props: {
    type: {
      type: Number,
      default: 0,
    },
    height: {
      type: Number,
      default: 500,
    },
    id: {
      type: String,
      default: "tinymceEditor",
    },
    value: {
      type: String,
      default: "",
    },
    disabledIn: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default:
        "link lists image code table wordcount media fullscreen preview paste indent2em",
    },
    toolbar: {
      type: [String, Array],
      default:
        "lineHeight|fontselect | bold italic underline strikethrough | link unlink image media | undo redo | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | indent2em outdent indent blockquote | code | removeformat",
    },
  },
  data() {
    return {
      uploadPrecent: 0,
      dialogVisible: false,
      list: [],
      loading: false,
      uploadUrl1: "/api/management/addNews/uploadfile",
      uploadUrl2: "/api/management/files/breakpoint-upload",
      editorId: this.id,
      newValue: "",
      editorInit: {
        language_url: "../../public/tinymce/zh_CN.js",
        language: "zh_CN",
        skin_url: "/public/tinymce/skins/ui/oxide/",
        content_css: "/public/tinymce/skins/content/default/content.css",
        height: this.height,
        content_style:
          "* { padding:0; margin:0; } img {max-width:100% !important; display: block; } video { max-width:100% !important; display: block; }",
        plugin_preview_width: 375, // 预览宽度
        plugin_preview_height: 668,
        lineheight_val:
          "1 1.1 1.2 1.3 1.35 1.4 1.5 1.55 1.6 1.75 1.8 1.9 1.95 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 3 3.1 3.2 3.3 3.4 4 5",
        fontsize_formats:
          "8px 10px 11px 12px 13px 14px 15px 16px 17px 18px 24px 36px",
        font_formats:
          "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
        plugins: this.plugins,
        indent2em_val: "2em", // 首行缩进
        powerpaste_word_import: "merge",
        toolbar: this.toolbar,
        paste_data_images: true,
        statusbar: true, // 底部的状态栏
        menubar: false, // 最上方的菜单
        branding: false, // 水印“Powered by TinyMCE”
        convert_urls: false, // 去除URL转换
        //     video_template_callback: function(data) {
        //     return '<video width="' + data.width + '" height="' + data.height
        //     + '"' + (data.poster ? ' poster="' + data.poster + '"' : '')
        //     + ' controls="controls">\n' + '<source src="' + '' + '"'
        //     + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n'
        //     + (data.source ? '<source src="' + '' + '"'
        //     + (data.sourcemime ? ' type="' + data.sourcemime + '"' : '') + ' />\n' : '')
        //     + '</video>';
        // },
        // 图片自定义上传
        images_upload_handler: (blobInfo, success, failure) => {
          console.log(blobInfo);
          const fileData = new FormData();
          fileData.append("file", blobInfo.blob());
          // this.dealFile(blobInfo)
          // return
          // 调用上传接口
          uploadfile(fileData).then(({ data, status, msg }) => {
            console.log(data, "data");
            if (data.msg == "SUCCESS") {
              success(data.data);
            } else {
              this.$message.error("上传失败");
            }
          });
        },
        file_picker_callback: (callback, value, meta) => {
          const _tath = this;
          var filetype =
            ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4";
          var materialType = "";
          switch (meta.filetype) {
            case "image":
              filetype = ".jpg, .jpeg, .png, .gif";
              materialType = "1";
              break;
            case "media":
              filetype = ".mp3, .mp4";
              break;
            case "file":
            default:
          }
          var input = document.createElement("input");
          input.setAttribute("type", "file");
          input.setAttribute("accept", filetype);
          input.click();
          let this_ = this;
          input.onchange = function() {
            var file = this.files[0];
            if (file.type == "video/mp4" || file.type.indexOf("video") != -1) {
              materialType = "3";
            } else if (
              file.type == "audio/mpeg" ||
              file.type == "audio/mp3" ||
              file.type.indexOf("audio") != -1
            ) {
              materialType = "2";
            }
            if (materialType == "1") {
              // 图片上传
              const fileData = new FormData();
              fileData.append("file", file);
              uploadfile(fileData).then(({ data, status, msg }) => {
                console.log(data, "data");
                if (data.msg == "SUCCESS") {
                  // 成功则将返回的url传入callback回调函数中
                  // callback 接受两个参数， url 和 图片名称
                  // 注意图片名称必须要传
                  callback(data.data, { title: file.name });
                } else {
                  this.$message.error("上传失败,请重新上传");
                }
              });
              input.value = "";
            } else {
              input.value = "";
              let fileSize = file.size / 1024 / 1024;
              console.log(fileSize, "100000");
              if(fileSize/1024>2){
               return this.$message.error('视频不能大于2G')
              }
              this.loading = true;
              const fileData = new FormData();
              fileData.append("file", file);
              fileData.append("materialType", materialType);
              let progressBox = document.getElementsByClassName(
                "tinymce-upload-progress-box"
              )[0];
              progressBox.style.display = "block";
              progressBox.style.visibility = "visible";
              // let dialog = document.createElement('div')//'.tox-dialog-wrap div[role="dialog"]';
              // dialog.classList.add('tox-dialog-wrap')
              // let progress = document.createElement("div")
              // progress.classList.add("tinymce-upload-progress")
              // let progressBar = document.createElement("div")
              // progressBar.classList.add("progress-bar");
              // let sourceBox = document.createElement("div").classList.add("tinymce-upload-progress-box")
              // console.log(dialog, progress, progressBar, "progressBar")
              // progressBar.appendChild(progress)
              // dialog.appendChild(progressBar)
              // progressBox.appendChild(dialog)
              // progress.style.display = 'block';
              let innier_upload_wrapper = document.getElementsByClassName(
                "innier-upload-wrapper"
              )[0];
              // let progress__text = document.getElementsByClassName('el-progress__text')[0]
              // my_upload(uploader) {
             
              if (fileSize > 100) {
                uploadByPieces({
                  file: file, //视频实体
                  pieceSize: 5, //分片大小
                  success: (data) => {
                    console.log(typeof data, data);
                    console.log(data, "编辑器里面上传视频");
                    if (
                      data &&
                      data.data &&
                      data.data.data &&
                      data.data.data.fileName
                    ) {
                      let fileName = data.data.data.fileName;
                      console.log("分片上传视频成功", data.data.data.fileName);
                      callback(baseUrl + "/upload/" + fileName, {
                        title: fileName,
                      });
                      // this.$message.success("上传完成");
                      input.value = "";
                      innier_upload_wrapper.innerHTML = "上传完成";
                      progressBox.style.display = "none";
                    } else if (typeof data == "number") {
                      innier_upload_wrapper.innerHTML = data + "%";
                      innier_upload_wrapper.style.backgroundSize = `${data}% 100%`;
                    } else if (data == "开始上传") {
                      innier_upload_wrapper.innerHTML = data;
                      innier_upload_wrapper.style.backgroundSize = `0% 100%`;
                    }
                  },
                  error: (e) => {
                    this.$message.error(e);
                    console.log(JSON.stringify(e), "编辑器里面上传视频2");
                    console.log("分片上传视频失败");
                  },
                });
              } else {
                // 第二种直接上传
                axios({
                  method: "post",
                  headers: {
                    "Content-Type": "multipart/form-data",
                  },
                  url: baseUrl + "/api/management/addNews/uploadfile", //自定义上传url
                  data: fileData,
                  onUploadProgress: (progressEvent) => {
                    let percent =
                      ((progressEvent.loaded / progressEvent.total) * 100) | 0;
                    console.log(percent, "hh");
                    this_.uploadPrecent = percent;
                    // progress__text.innerHTML = percent + '%'
                    innier_upload_wrapper.innerHTML = percent + "%";
                    innier_upload_wrapper.style.backgroundSize = `${this_.uploadPrecent}% 100%`;
                    if (this_.uploadPrecent == 100) {
                      progressBox.style.display = "none";
                    }
                  },
                })
                  .then((res) => {
                    input.value = "";
                    if (res.data.msg == "SUCCESS") {
                      callback(res.data.data, { title: file.name });
                      this_.$message.success("上传完成");
                    } else {
                      this_.$message.error("直接上传失败");
                    }
                  })
                  .catch((err) => {
                    input.value = "";
                    this_.$message.error("直接上传失败");
                    console.log(err);
                  });
              }
              this.loading = false;
              input.value = "";
            }
          };
        },
      },
      // editorId: this.id,
      // newValue: "",
    };
  },
  computed: {
    innerUploadStyle() {
      return `background-size: ${this.uploadPrecent}% 100%;`;
    },
    editorValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.newValue = val;
      },
    },
  },
  watch: {
    newValue(newValue) {
      this.$emit("input", newValue);
    },
  },
  mounted() {
    // this.beforeInit()
  },
  beforeDestroy() {
    this.clear();
  },
  methods: {
    clear() {
      this.editorValue = "";
    },
  },
};
</script>

<style scoped>
.tinymce-upload-progress-box {
  position: fixed;
  background-color: #ffffffbf;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  /* display: none; */
  visibility: hidden;
  z-index: 99991;
}

.display-upload-wrapper {
  border: 1px solid #207ab7;
  width: 100%;
  text-align: center;
  height: 20;
  border-radius: 0px;
  background: #f4f8ff;
}

.innier-upload-wrapper {
  height: 100%;
  background: linear-gradient(270deg, #c0d8ff 0%, #207ab7 100%);
  background-repeat: no-repeat;
  background-size: 10% 100%;
  transition: background-size 0.3s linear;
}

/* .tox-dialog-wrap .progress-bar {
  position: absolute;
  background-color: #ffffffbf;
  width: 100%;
  height: 100%;
  z-index: 99991;
} */

.tinymce-upload-progress {
  position: fixed !important;
  text-align: center;
  /* display: none; */
  top: 50%;
  left: 50%;
  z-index: 99991;
  margin-top: -62px !important;
  margin-left: -63px !important;
}
</style>
